<?php

namespace app\admin\controller;


use app\common\model\AdminModel;
use app\common\model\TouziProductOrder;
use app\common\model\UserAddress;
use app\common\model\User;
use app\common\model\HomeTokenModel;
use app\common\model\LoginLog;
use app\common\model\UserRealName;
use app\common\model\UserBank;
use app\common\model\User as models;
use app\common\traites\PublicCrudTrait;
use app\validate\User as validates;
use think\exception\ValidateException;
use think\facade\Db;

class Member extends Base
{
    protected $model;
    use PublicCrudTrait;

    public function initialize()
    {
        $this->model = new models();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    //获取列表信息
    public function index()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件
        $post = array_filter($this->request->post());
        $map = $date = [];
        isset($post['user_name']) && $map [] = ['b.user_name', 'like', '%' . $post['user_name'] . '%'];
        isset($post['phone']) && $map[] = ['b.phone', '=', $post['phone']];
        isset($post['id']) && $map[] = ['b.id', '=', $post['id']];
        isset($post['invitation_code']) && $map[] = ['b.invitation_code', '=', $post['invitation_code']];
        isset($post['market_uid']) && $map [] = ['b.market_uid', '=',$post['market_uid']];

        if (isset($post['start']) && isset($post['end'])) {
            $date['start'] = $post['start'];
            $date['end'] = $post['end'];
        }

        $list = $this->model->page_list($map, $limit, $page, $date);
        return $this->success($list);
    }
    /**
     * 获取代理信息
     * */
    public function agent_data(){
        $AdminModel=new AdminModel();
        $res=$AdminModel->field('id,user_name')->where('role',2)->select();
        return $this->success($res);
    }

    public function getAddress(){
        $user_id = $this->request->post('user_id');
        $address =(new UserAddress())->where(['uid'=>$user_id])->find();
        return $this->success($address);
    }
    //代理商个人信息
    public function agent()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        $list= $this->model->page_one($limit,$page);
        return $this->success($list);
    }
    public function add()
    {
        //过滤数据
        $postField = 'product_class,phone,market_uid,user_name,money_balance,money_freeze,agent_rate,pwd,withdraw_pwd,nickname,type,status,is_real_name,is_fictitious,invitation_code';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        $post['user_name'] = $post['phone'];
        $post['nickname'] = $post['phone'];
        $post['true_name'] = $post['phone'];

       if (!$post || empty($post['market_uid'])) return $this->failed('业务员ID错误或不存在');
        //验证数据
        try {
            validate(validates::class)->scene('add')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        //查询是否重复的用户名
        $find = $this->model->where('phone', $post['phone'])->find();
        if ($find) return $this->failed('用户已存在');

        //加密密码
        $post['pwd'] = !empty($post['pwd']) && isset($post['pwd']) ? pwdEncryption($post['pwd']) :home_Initial_pwd();
        $post['withdraw_pwd'] = !empty($post['withdraw_pwd']) && isset($post['withdraw_pwd']) ? pwdEncryption($post['withdraw_pwd']) :home_Initial_pwd();
        //邀请码不存在时邀请码
        if (!isset($post['invitation_code']) || empty($post['invitation_code']))  $post['invitation_code'] = $this->rand_code();
//        if (!isset($post['agent_rate']) || empty($post['agent_rate'])) $post['agent_rate']=0;
//        if ($post['agent_rate'] >100) return  $this->failed('分销比例不能大于100');
//
//        //判断是否是代理商添加。是就给该用户加上 代理id
//        if (session('admin_user.agent')){
//            $post['agent_id_1']=session('admin_user.id');
//            $post['agent_id_2']=session('admin_user.agent_id_1');
//            $post['agent_id_3']=session('admin_user.agent_id_2');
//            $post['market_uid']=session('admin_user.market_uid');
//            //查询当前服务商添加的 服务商的 分销比例是否小于 100%
//            $agent_rate =$this->model->where(['agent_id_1|agent_id_2|agent_id_3|id' => session('admin_user.id')])->sum('agent_rate');
//
//            if ((intval($agent_rate)+intval($post['agent_rate'])) >100)  return  $this->failed('分销比例'.($agent_rate+$post['agent_rate']).'%不能超过100%');
//            if (session('admin_user.agent_rate') <= $post['agent_rate'])  return  $this->failed('分销比例不能大于自己');
//        }

        //执行修改数据
        $save = $this->model->save($post);
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }

    /**
     * 修改方法
     * @return mixed
     */
    public function edit()
    {
        //过滤数据
        $postField = 'product_class,agent_id_1,phone,market_uid,user_name,pwd,withdraw_pwd,nickname,type,id';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        $post['user_name'] = $post['phone'];
        $post['nickname'] = $post['phone'];

        //验证数据
        try {
            validate(validates::class)->scene('edit')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        //查询是否重复的用户名
        $find = $this->model->where('phone', $post['phone'])->where('id', '<>', $post['id'])->find();
        if ($find) return $this->failed('用户已存在');

      //加密密码
        if (!empty($post['pwd'])){
            $post['pwd'] = pwdEncryption($post['pwd']);
        }else{
            unset($post['pwd']);
        }

        if (!empty($post['withdraw_pwd'])){
            $post['withdraw_pwd'] = pwdEncryption($post['withdraw_pwd']);
        }else{
            unset($post['withdraw_pwd']);
        }
        //执行修改数据
        $save = $this->model->update($post);
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    public function rand_code(){
        $rand =userzm(6);
        $qc = $this->model->where('invitation_code',$rand)->find();
        if ($qc){
            $this->rand_code();
        }else{
            return $rand;
        }
    }

    //判断业务员存不存在
    public function is_admin($post)
    {
        if (!isset($post['market_uid']) || empty($post['market_uid'])) return false;
        $admin = (new AdminModel())->find($post['market_uid']);
        if (!$admin) return false;
        return $post;
    }

    //修改虚拟账号
    public function is_status()
    {
        $id = $this->request->post('id', 0);
        if ($id <= 0) return $this->failed('用户不存在');
        $find = $this->model->find($id);
        $find->is_fictitious = $find->is_fictitious == 1 ? 0 : 1;
        $save = $find->save();
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }

    // 用户状态
    public function is_status_user()
    {
        $id = $this->request->post('id', 0);
        if ($id <= 0) return $this->failed('用户不存在');
        $find = $this->model->find($id);
        $find->status_user = $find->status_user == 1 ? 0 : 1;
        $save = $find->save();
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    
    public function is_real_name()
    {
        $id = $this->request->post('id', 0);
        if ($id <= 0) return $this->failed('用户不存在');
        $find = $this->model->find($id);
        $find->is_real_name = $find->is_real_name == 1 ? 0 : 1;
        $save = $find->save();
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    // 提现状态
    public function is_status_money()
    {
        $id = $this->request->post('id', 0);
        if ($id <= 0) return $this->failed('用户不存在');
        $find = $this->model->find($id);
        $find->status_money = $find->status_money == 1 ? 0 : 1;
        $save = $find->save();
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    // 转账状态
    public function is_status_transfer()
    {
        $id = $this->request->post('id', 0);
        if ($id <= 0) return $this->failed('用户不存在');
        $find = $this->model->find($id);
        $find->status_transfer = $find->status_transfer == 1 ? 0 : 1;
        $save = $find->save();
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    // 收益状态
    public function is_status_income()
    {
        $id = $this->request->post('id', 0);
        if ($id <= 0) return $this->failed('用户不存在');
        $find = $this->model->find($id);
        $find->status_income = $find->status_income == 1 ? 0 : 1;
        $save = $find->save();
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    /**
     * money_change_type: 1 1增加
     *uid: 20  用户id
     *change_money:  变化金额
     *money_ststus: 90 90余额修改
     *用户余额修改
     */
    public function money_edit()
    {
        $postField = 'money_change_type,change_money,uid,money_status,money_mark';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        $post = array_filter($post);
        //验证数据
        try {
            validate(validates::class)->scene('money')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        //查询当前用户的余额
        $find = $this->model->find($post['uid']);
        if (!$find) return $this->failed('用户不存在');

        return $this->money_do_edit($post, $find);

    }

    public function caijin()
    {
        $postField = 'money_type,money,uid,money_mark';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        $post = array_filter($post);
        //验证数据
        // try {
        //     validate(validates::class)->scene('money')->check($post);
        // } catch (ValidateException $e) {
        //     // 验证失败 输出错误信息
        //     return $this->failed($e->getError());
        // }
        //查询当前用户的余额
        $find = $this->model->find($post['uid']);
        if (!$find) return $this->failed('用户不存在');
        $data = [];
        $data['money_status'] = $post['money_type'];
        $data['change_money'] = $post['money'];
        $data['money_change_type'] = 1;
        $data['money_mark'] = $post['money_mark'];

        return $this->money_do_edit($data, $find);

    }
    public function product_order_list()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件
        $post = array_filter($this->request->post());
        $map = $date = [];
        isset($post['uid']) && $map[] = ['user_id', '=', $post['uid']];
        // if (isset($post['start']) && isset($post['end'])) {
        //     $date['start'] = $post['start'];
        //     $date['end'] = $post['end'];
        // }

        $list = (new TouziProductOrder)->page_list($map, $limit, $page, $date);
        return $this->success($list);

    }
    public function t_xiaxian()
    {
        $postField = 'uid';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        $post = array_filter($post);
        //查询当前用户的余额
        $find = $this->model->find($post['uid']);
        if (!$find) return $this->failed('用户不存在');

        (new HomeTokenModel)->where(['user_id'=> $post['uid']])->delete();
        $this->model->where(['id'=>$post['uid']])->update(['state'=>0]); // 更新下线状态
        return $this->success([]);
    }
    public function iplist()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件
        $post = array_filter($this->request->post());
        $map = $date = [];
        isset($post['uid']) && $map[] = ['unique', '=', $post['uid']];
        $list = (new LoginLog)->page_list($map, $limit, $page, $date);
        return $this->success($list);
    }

    public function updateIDCard(){
        $post = $this->request->post();
        if($post['id'] == ''){
            (new UserRealName)->save($post);
        }else{
            $data = [];
            $data['true_name'] = $post['true_name'];
            $data['card_id'] = $post['card_id'];
            $r = (new UserRealName)->where(['id'=>$post['id']])->update($data);
        }
        return $this->success([]);
    }

    public function updateBankCard(){
        //过滤数据
        $postField = 'card_number,bank_name,true_name,id,bank_address,user_id';
        $post   = $this->request->only(explode(',', $postField), 'post', null);

        if(empty($post['id'])){
            (new UserBank)->insert($post);
        }else{
            $data = [];
            $data['bank_address'] = $post['bank_address'];
            $data['card_number'] = $post['card_number'];
            $data['bank_name'] = $post['bank_name'];
            $data['true_name'] = $post['true_name'];
            $data['user_id'] = $post['user_id'];
            $r = (new UserBank)->where(['id'=>$post['id']])->update($data);
            // dump($r);
        }
        return $this->success([$post]);
    }
    
    /**
     * 本地用户余额修改
     * @param $post /数据
     * @param $find /模型查询数据
     * @return mixed
     */
    protected function money_do_edit($post, $find)
    {
        $balance_start = $find->money_balance;       
        if ($post['money_status'] == 'money_balance') {
            $balance_start = $find->money_balance;
        }

        if ($post['money_status'] == 'money_gongfu') {
            $balance_start = $find->money_gongfu;
        }

        if ($post['money_status'] == 'money_cishan') {
            $balance_start = $find->money_cishan;
        }

        if ($post['money_status'] == 'money_guozhai') {
            $balance_start = $find->money_guozhai;
        }

        if ($post['money_status'] == 'money_juanzeng') {
            $balance_start = $find->money_juanzeng;
        }

        if ($post['money_status'] == 'money_zhifu') {
            $balance_start = $find->money_zhifu;
        }
        //查询用户钱是否够扣
        if ($balance_start < $post['change_money'] && $post['money_change_type'] != 1) return $this->failed('用户钱包不够');
        //state是 1时是增加
        $balance_end = $post['money_change_type'] == 1 ? $balance_start + $post['change_money'] : $balance_start - $post['change_money'];
        $change_type = 101;
        if($post['money_change_type'] == 1){
            $change_type = 101;
        }else{
            $change_type = 201;
        }

        if ($post['money_status'] == 'money_balance') {
            $find->money_balance = $balance_end;
        }

        if ($post['money_status'] == 'money_gongfu') {
            $find->money_gongfu = $balance_end;
        }

        if ($post['money_status'] == 'money_cishan') {
            $find->money_cishan = $balance_end;
        }

        if ($post['money_status'] == 'money_guozhai') {
            $find->money_guozhai = $balance_end;
        }

        if ($post['money_status'] == 'money_juanzeng') {
            $find->money_juanzeng = $balance_end;
        }

        if ($post['money_status'] == 'money_zhifu') {
            $find->money_zhifu = $balance_end;
        }
        //执行修改数据
        $save = false;
        Db::startTrans();
        try {
            $find->save();
            //写操作日志
            (new \app\common\model\MoneyLog())->insert([
                'create_time' => date('Y-m-d H:i:s'),
                'type' => 3,
                'status' => $change_type,
                'money_before' => $balance_start,
                'money_end' => $balance_end,
                'money' => $post['change_money'],
                'money_type' => $post['money_status'],
                'mark' => $post['money_mark'],
                'uid' => $find->id,
                'market_uid' => session('admin_user.id'),
            ]);
            $save = true;
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
    
/**
     * 团队列表
     * */
    public function team_list(){
        //获取缓存
        $postField = 'user_name,start,end';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        if (!isset($post['user_name'])){
            return $this->failed('无效参数');
        }
        
        // 第一步 获取ID
        $map_find = [];
        $map_find['user_name'] = $post['user_name'];
        $User=new User();
        $firstUserInfo = $User->where($map_find)->find();

        
        
        // 增加时间段 判断
        $uids = [];
        if (isset($post['start']) && $post['start'] != '' && isset($post['end']) && $post['end'] != '' ) {
            $date['start'] = $post['start'];
            $date['end'] = $post['end'];
            // 第一步 获取ID
            $users = $User->whereBetweenTime('create_time', $date['start'], $date['end'])->select();
            foreach ($users as $k =>$v){
                $uids[] = $v->id;
            }
        }
        $uids_str = implode(',', $uids);
        
        
        $firstUserId = $firstUserInfo['id'];
        // 第二步 获取 一级
        $map_v1 = [];
        if(isset($uids) && count($uids)>1){
            $map_v1[] = ['u.id','in',$uids_str];
        }
        $map_v1[] = ['u.agent_id_1','=',$firstUserId];
        $yiji = $User->alias('u')
            ->join('touzi_team_tongji t', 'u.id = t.user_id','left')
            ->where($map_v1)
            // ->limit(20)
            ->select()            
            ->toArray();

        $returnData_1 = [];
        
        foreach($yiji as $k_1 => $v_1){

            $v_1['true_name'] = getTrueName($v_1['id']);
            $v_1['agent_id_1_phone'] = getPhoneById($v_1['agent_id_1']);
            $v_1['agent_id_1_true_name'] = getTrueName($v_1['agent_id_1']);

            $returnDataTemp_1 = [];
            $returnDataTemp_1['info'] = $v_1;
            $returnDataTemp_1['user_name'] = $v_1['user_name'];
            $returnDataTemp_1['create_time'] = $v_1['create_time'];
            $returnDataTemp_1['status_user'] = $v_1['status_user'];
            $returnDataTemp_1['id'] = $v_1['id']; // 进行排序
            
            // 第三步 获取 二级 循环
            $map_v2 = [];
            if(isset($uids)){
                $map_v2[] = ['u.id','in',$uids_str];
            }
            // $map_v2['u.agent_id_1'] = $v_1['id'];
            $map_v2[] = ['u.agent_id_1','=',$v_1['id']];
            $erji = $User->alias('u')
                ->join('touzi_team_tongji t', 'u.id = t.user_id','left')
                ->where($map_v2)
                // ->limit(20)
                ->select()
                ->toArray();
            $returnData_2 = [];
            
            foreach($erji as $k_2 => $v_2){

                $v_2['true_name'] = getTrueName($v_2['id']);
                $v_2['agent_id_1_phone'] = getPhoneById($v_2['agent_id_1']);
                $v_2['agent_id_1_true_name'] = getTrueName($v_2['agent_id_1']);

                $returnDataTemp_2 = [];
                $returnDataTemp_2['info'] = $v_2;
                $returnDataTemp_2['user_name'] = $v_2['user_name'];
                $returnDataTemp_2['create_time'] = $v_2['create_time'];
                $returnDataTemp_2['status_user'] = $v_2['status_user'];
                $returnDataTemp_2['id'] = $v_2['id']; // 进行排序
                
    
                // 第三步 获取 三级 循环
                $map_v3 = [];
                if(isset($uids)){
                    $map_v3[] = ['u.id','in',$uids_str];
                }
                // $map_v3['u.agent_id_1'] = $v_2['id'];
                $map_v3[] = ['u.agent_id_1','=',$v_2['id']];
                $sanji = $User->alias('u')
                    ->join('touzi_team_tongji t', 'u.id = t.user_id','left')
                    ->where($map_v3)
                    // ->limit(20)
                    ->select()
                    ->toArray();
                $returnData_3 = [];
                foreach($sanji as $k_3 => $v_3){

                    $v_3['true_name'] = getTrueName($v_3['id']);
                    $v_3['agent_id_1_phone'] = getPhoneById($v_3['agent_id_1']);
                    $v_3['agent_id_1_true_name'] = getTrueName($v_3['agent_id_1']);

                    $returnDataTemp_3 = [];
                    $returnDataTemp_3['info'] = $v_3;
                    $returnDataTemp_3['user_name'] = $v_3['user_name'];
                    $returnDataTemp_3['create_time'] = $v_3['create_time'];
                    $returnDataTemp_3['status_user'] = $v_3['status_user'];
                    $returnDataTemp_3['id'] = $v_3['id']; // 进行排序
                    $returnData_3[] = $returnDataTemp_3;
                }
                if(!empty($returnData_3)){
                    $returnDataTemp_2['children'] = $returnData_3;
                }
                
                $returnData_2[] = $returnDataTemp_2;
            }
            if(!empty($returnData_2)){
                $returnDataTemp_1['children'] = $returnData_2;
            }
            
            $returnData_1[] = $returnDataTemp_1;
        }
        
        return $this->success($returnData_1);

    }

    /**
     * 团队 封禁 解封 
     * */
    public function team_feng(){
        
        //获取缓存
        $postField = 'user_name,status_user';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        if (!isset($post['user_name'])){
            return $this->failed('无效参数');
        }
        $map = [];
        $map['user_name'] = $post['user_name'];
        $User=new User();
        // 第一步 获取ID
        $firstUserInfo = $User->where($map)->find();
        $firstUserId = $firstUserInfo['id'];
        // 第二步 获取 一级
        $map1 = [];
        $map1['agent_id_1'] = $firstUserId;
        $map2 = [];
        $map2['agent_id_2'] = $firstUserId;
        $map3 = [];
        $map3['agent_id_3'] = $firstUserId;
        $data= [];
        $data['status_user'] = $post['status_user'];
        $userids =$User->field('id')->where($map)->whereOr($map1)->whereOr($map2)->whereOr($map3)->select()->toArray();
        $userids_arr = [];
        foreach($userids as $k => $v){
            $userids_arr[] = $v['id'];
        }
        $userids_str = implode(',', $userids_arr); 
        // return $this->success($userids_str);
        if($post['status_user'] == 0){
            $data['state'] =  0;
            $map_token = [];
            $map_token[] = array('user_id','in',$userids_str);
            (new HomeTokenModel)->where($map_token)->delete();
        }
        $map_update = [];
        $map_update[] = array('id','in',$userids_str);
        $User->where($map_update)->update($data);
        return $this->success([]);
    }
    /**
     * 团队 统计展示
     * 非时间累计版本 
     * */
    public function team_show(){
        //获取缓存
        $postField = 'user_name,tg_start,tg_end';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        if (!isset($post['user_name'])){
            return $this->failed('无效参数');
        }
        $map = [];
        $map_date = [];
        $map['user_name'] = $post['user_name'];
        // dump($post);
        if($post['tg_start'] && $post['tg_end']){
            $time_start = date('Y-m-d H:i:s',strtotime($post['tg_start']));
            $time_end = date('Y-m-d H:i:s',strtotime($post['tg_end']));
            $map_date = [$time_start,$time_end];
        }
        // dump($map_date);
        // return $this->success($map_date);
        
        $userInfo = (new User)->where($map)->find();
        $uid = $userInfo->id;       

        $returnData = [];
        $returnData[] = [
            'level' => '一级',
            'recharge_agent' => Tongji_recharge_agent($uid, '1',$map_date),
            'withdraw_agent' => Tongji_withdraw_agent($uid, 1,$map_date),
            'buy_money_agent' => Tongji_buy_money_agent($uid, '1',$map_date),
            'team_has_nums' => Tongji_team_has_nums($uid, '1',$map_date),
            'team_real_name_nums' => Tongji_team_real_name_nums($uid, '1',$map_date),
            'team_firstbuy_nums' => Tongji_team_firstbuy_nums($uid, '1',$map_date),
            'team_allbuy_nums' => Tongji_team_allbuy_nums($uid, '1',$map_date),
        ];
        // return $this->success($returnData);
        $returnData[] = [
            'level' => '二级',
            'recharge_agent' => Tongji_recharge_agent($uid, '2',$map_date),
            'withdraw_agent' => Tongji_withdraw_agent($uid, 2,$map_date),
            'buy_money_agent' => Tongji_buy_money_agent($uid, '2',$map_date),
            'team_has_nums' => Tongji_team_has_nums($uid, '2',$map_date),
            'team_real_name_nums' => Tongji_team_real_name_nums($uid, '2',$map_date),
            'team_firstbuy_nums' => Tongji_team_firstbuy_nums($uid, '2',$map_date),
            'team_allbuy_nums' => Tongji_team_allbuy_nums($uid, '2',$map_date),
        ];
        // return $this->success($returnData);
        $returnData[] = [
            'level' => '三级',
            'recharge_agent' => Tongji_recharge_agent($uid, '3',$map_date),
            'withdraw_agent' => Tongji_withdraw_agent($uid, 3,$map_date),
            'buy_money_agent' => Tongji_buy_money_agent($uid, '3',$map_date),
            'team_has_nums' => Tongji_team_has_nums($uid, '3',$map_date),
            'team_real_name_nums' => Tongji_team_real_name_nums($uid, '3',$map_date),
            'team_firstbuy_nums' => Tongji_team_firstbuy_nums($uid, '3',$map_date),
            'team_allbuy_nums' => Tongji_team_allbuy_nums($uid, '3',$map_date),
        ];
        $returnData[] = [
            'level' => '123合',
            'recharge_agent' => Tongji_recharge_agent($uid, 'n',$map_date),
            'withdraw_agent' => Tongji_withdraw_agent($uid, 'n',$map_date),
            'buy_money_agent' => Tongji_buy_money_agent($uid, 'n',$map_date),
            'team_has_nums' => Tongji_team_has_nums($uid, 'n',$map_date),
            'team_real_name_nums' => Tongji_team_real_name_nums($uid, 'n',$map_date),
            'team_firstbuy_nums' => Tongji_team_firstbuy_nums($uid, 'n',$map_date),
            'team_allbuy_nums' => Tongji_team_allbuy_nums($uid, 'n',$map_date),
        ];
        $returnData[] = [
            'level' => '无限',
            'recharge_agent' => Tongji_recharge_agent($uid, 'w',$map_date),
            'withdraw_agent' => Tongji_withdraw_agent($uid, 'w',$map_date),
            'buy_money_agent' => Tongji_buy_money_agent($uid, 'w',$map_date),
            'team_has_nums' => Tongji_team_has_nums($uid, 'w',$map_date),
            'team_real_name_nums' => Tongji_team_real_name_nums($uid, 'w',$map_date),
            'team_firstbuy_nums' => Tongji_team_firstbuy_nums($uid, 'w',$map_date),
            'team_allbuy_nums' => Tongji_team_allbuy_nums($uid, 'w',$map_date),
        ];

        return $this->success($returnData);
    }

    /**
     * 团队 统计展示
     * 非时间累计版本 
     * */
    public function team_show_v1(){
        //获取缓存
        $postField = 'user_name,';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        if (!isset($post['user_name'])){
            return $this->failed('无效参数');
        }
        $map = [];
        $map['user_name'] = $post['user_name'];
        $User=Db::name('touzi_team_tongji');
        // 第一步 获取ID
        $firstUserInfo = $User->where($map)->find();
        $returnData = [];
        $returnData[] = [
            'level' => '一级',
            'recharge_agent' => $firstUserInfo['recharge_agent_1'],
            'withdraw_agent' => $firstUserInfo['withdraw_agent_1'],
            'buy_money_agent' => $firstUserInfo['buy_money_agent_1'],
            'team_has_nums' => $firstUserInfo['team_has_nums_1'],
            'team_real_name_nums' => $firstUserInfo['team_real_name_nums_1'],
            'team_firstbuy_nums' => $firstUserInfo['team_firstbuy_nums_1'],
            'team_allbuy_nums' => $firstUserInfo['team_allbuy_nums_1'],
        ];
        $returnData[] = [
            'level' => '二级',
            'recharge_agent' => $firstUserInfo['recharge_agent_2'],
            'withdraw_agent' => $firstUserInfo['withdraw_agent_2'],
            'buy_money_agent' => $firstUserInfo['buy_money_agent_2'],
            'team_has_nums' => $firstUserInfo['team_has_nums_2'],
            'team_real_name_nums' => $firstUserInfo['team_real_name_nums_2'],
            'team_firstbuy_nums' => $firstUserInfo['team_firstbuy_nums_2'],
            'team_allbuy_nums' => $firstUserInfo['team_allbuy_nums_2'],
        ];
        $returnData[] = [
            'level' => '三级',
            'recharge_agent' => $firstUserInfo['recharge_agent_3'],
            'withdraw_agent' => $firstUserInfo['withdraw_agent_3'],
            'buy_money_agent' => $firstUserInfo['buy_money_agent_3'],
            'team_has_nums' => $firstUserInfo['team_has_nums_3'],
            'team_real_name_nums' => $firstUserInfo['team_real_name_nums_3'],
            'team_firstbuy_nums' => $firstUserInfo['team_firstbuy_nums_3'],
            'team_allbuy_nums' => $firstUserInfo['team_allbuy_nums_3'],
        ];
        $returnData[] = [
            'level' => '全部',
            'recharge_agent' => $firstUserInfo['recharge_agent_n'],
            'withdraw_agent' => $firstUserInfo['withdraw_agent_n'],
            'buy_money_agent' => $firstUserInfo['buy_money_agent_n'],
            'team_has_nums' => $firstUserInfo['team_has_nums_n'],
            'team_real_name_nums' => $firstUserInfo['team_real_name_nums_n'],
            'team_firstbuy_nums' => $firstUserInfo['team_firstbuy_nums_n'],
            'team_allbuy_nums' => $firstUserInfo['team_allbuy_nums_n'],
        ];

        return $this->success($returnData);
    }
   /**
     * 排行榜
     * */
    public function ranking(){
        //获取缓存
        $postField = 'search_type,order_list,market_uid,time_start,time_end';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        if (!isset($post['search_type'])){
            return $this->failed('无效参数');
        }
        $map = [];
        if ($post['order_list']==0){
            $order='desc';  // 排序 倒序
        }else{
            $order='asc'; // 排序 正序
        }
        if (!empty($post['market_uid'])){
            $map['market_uid'] = $post['market_uid'];
        }
        // 增加 代理商 推广列表 ---> 对于代理商 只能 搜索 他自己的
        if (session('admin_user.role')==2){
            $map['market_uid'] = $post['market_uid'];
        }

        // 其实这个是 无法根据时间 进行排序的  ---> 已经是统计过的数据了 
        // if (isset($post['start']) && isset($post['end'])) {
        //     $date['start'] = $post['start'];
        //     $date['end'] = $post['end'];
        // }

        
        // $User=new User();
        // $way=0; // 很蠢的 写法 看看 是否要去补充 用户名跟手机号

        // 累计充值金额
        if($post['search_type'] == 'charge_money'){
            $res= Db::name('touzi_team_tongji')->where($map)->order('recharge_money_all '.$order.'')->limit(0,30)->select()->toArray();
        }
        // 累计提现金额
        if($post['search_type'] == 'withdraw_money'){
            $res= Db::name('touzi_team_tongji')->where($map)->order('withdraw_money_all '.$order.'')->limit(0,30)->select()->toArray();
        }
         
        // if($post['type']==2){
        //     //用户购买产品总金额 本都货币
        //     $res= Db::name('touzi_product_order')->alias('a')->join('common_user b', 'a.user_id = b.id', 'left')->where($map)->field('a.user_id,sum(buy_price) as num')->group('a.user_id')->order('num '.$order.'')->limit(0,100)->select()->toArray();
        // }else{
        //     //邀请人数
        //     $res= Db::name('common_user')->alias('b')->join('common_pay_money_log c', 'c.uid = b.id', 'left')->where($map)->where(['c.status'=>104])->field('b.id,b.user_name,b.phone,count(c.uid) as num')->group('c.uid')->order('num '.$order.'')->limit(0,100)->select()->toArray();
        //     $way=1;
        // }
      
        // if ($res){
        //     foreach ($res as $k=>$v){
        //         if ($way==0){
        //             $res_user=$user->field('user_name,phone')->where('id',$v['user_id'])->find();
        //             $res[$k]['user_name']=$res_user['user_name']??'';
        //             $res[$k]['phone']=$res_user['phone']??'';
        //         }
        //         $res[$k]['sort']=$k+1;
        //     }
        // }
        return $this->success($res);
    }

}